package com.junxonline.instant.job.handler;

import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import com.junxonline.instant.dao.entity.model.device.Terminal;
import com.junxonline.instant.dao.mapper.device.TerminalMapper;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;

/**
 * 终端状态监测任务
 *
 * @author JunX
 * @date 2021-11-12
 */
@Log4j2
@Component
public class TerminalStatusJob {

    @Autowired
    private TerminalMapper terminalMapper;

    @XxlJob("terminalStatusJob")
    public ReturnT<String> terminalStatusJob() {
        log.info("-------开始执行[终端状态监测任务]-------");
        try {
            refreshTerminalStatus();
            log.info("-------[终端状态监测任务]执行成功-------");
        } catch (Exception e) {
            log.error("-------[终端状态监测任务]执行出错-------");
            e.printStackTrace();
            return ReturnT.FAIL;
        }
        return ReturnT.SUCCESS;
    }

    private void refreshTerminalStatus() {
        // 查找所有终端
        List<Terminal> terminalList = terminalMapper.selectList(null);
        for (Terminal terminal : terminalList) {
            Date today = DateUtil.date();
            // 对比心跳时间是否超时
            Date heartBeatTime = terminal.getHeartBeatTime();
            // 超时的将状态刷新为离线
            if (DateUtil.between(today, heartBeatTime, DateUnit.MINUTE) >= 1) {
                // 超过7天未在线刷为多日离线状态
                Date sevenDayDate = DateUtil.offsetDay(today, -7);
                if (DateUtil.between(heartBeatTime, sevenDayDate, DateUnit.DAY) >= 7) {
                    terminalMapper.updateStatusByCode(3, terminal.getCode());
                } else {
                    terminalMapper.updateStatusByCode(0, terminal.getCode());
                }
            }
        }
    }

}
